//
//  HJOtherDynamic.m
//  project
//
//  Created by jc on 2019/5/10.
//  Copyright © 2019 健健. All rights reserved.
//

#import "HJOtherDynamic.h"
#import "AVPlayerManager.h"
#import "HJPlayerView.h"
#import "YFMineCellViewModel.h"
#import "YFDongtaiModel.h"

@interface HJOtherDynamic ()<HJVideoPlayerDelegate>//HJAVPlayerViewDelegate
@property (nonatomic, assign) BOOL isPlayerReady;
@property (weak, nonatomic) IBOutlet UILabel *content;
@property (weak, nonatomic) IBOutlet UILabel *time;
@property (weak, nonatomic) IBOutlet UIButton *zanBtn;
@property (nonatomic,strong,nonnull) SDCycleScrollView * sdCycleView;
@property (nonatomic,strong) HJPlayerView * playerView;// 播放层

@property (weak, nonatomic) IBOutlet UIImageView *bgImage;
@property (nonatomic,strong) NSString * zanNum;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;

/**
 播放层
 */
@property (nonatomic, strong) HJVideoPlayer *player;

@end

@implementation HJOtherDynamic

-(void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES];
}

-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self.navigationController setNavigationBarHidden:NO];
    [self pause];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    @weakify(self)
    [[self.zanBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        //if (self.isMine) return;
        self.zanBtn.userInteractionEnabled = NO;
        int zannum = self.zanBtn.titleLabel.text.intValue;
        x.selected = !self.zanBtn.selected;
        if (x.selected) {
            zannum++;
        }else {
            zannum--;
        }
        NSString * url = [Api stringByAppendingString:PraiseApi];
        NSMutableDictionary * params = [NSMutableDictionary dictionary];
        params[@"userId"] = [HJUserManager getUserModel].userId;
        params[@"albumId"] = self->_cellModel.albumId;
        WS(weakSelf)
        [HJHttpTool post:url params:params success:^(HJResponeds *result) {
            dispatch_async(dispatch_get_main_queue(), ^{
                weakSelf.zanBtn.selected = x.selected;
                [self.zanBtn setTitle:[NSString stringWithFormat:@"%d",zannum] forState:0];
                self.zanNum = [NSString stringWithFormat:@"%d",zannum];
                if (!self.isMine) {
                    weakSelf.zanBtn.userInteractionEnabled = YES;
                }
                if (self.didBackBtnClicked && self.isMine) {
                    self.didBackBtnClicked(self.zanNum,self.zanBtn.selected,self.isMine);
                }
                
            });
        } failure:^(id result) {
            [self showErrorHUDWithError:result];
        }];
    }];
    
    [[self.backBtn rac_signalForControlEvents:UIControlEventTouchUpInside]subscribeNext:^(__kindof UIControl * _Nullable x) {
        @strongify(self)
        self.isMine = NO;
        if (self.didBackBtnClicked ) {
            self.didBackBtnClicked(self.zanNum,self.zanBtn.selected,self.isMine);
        }
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

-(void)setCellModel:(YFMineCellViewModel *)cellModel {
    _cellModel = cellModel;
    dispatch_async(dispatch_get_main_queue(), ^{
        self.content.attributedText = cellModel.attributeTitle;
        self.time.text = cellModel.model.time;
    
        [self.zanBtn setTitle:cellModel.praiseAmount forState:(UIControlStateNormal)];
        self.zanBtn.selected = cellModel.isPraise;
        self.bgImage.clipsToBounds = YES;
        if (cellModel.isImage) {
            self.bgImage.hidden = YES;
            NSMutableArray * imageArr = [NSMutableArray array];
            for (YFDongtaiFileModel * fileModel in cellModel.model.files) {
                if ([fileModel.fileType isEqualToString:@"image"]) {
                    [imageArr addObject:fileModel.url];
                }
            }
            self.sdCycleView.imageURLStringsGroup = imageArr;
        }else {
//            [self.bgImage sd_setImageWithURL:[NSURL URLWithString:cellModel.model.files[0].thumbnail]];
//            [self setPlayerWithUrl:cellModel.videoURL];
            [self.player playVideoWithView:self.bgImage url:cellModel.videoURL];
        }
        [UIView animateWithDuration:0.1 animations:^{
            [self.view layoutIfNeeded];
        }];
    });
}

//- (void)play {
//    [_playerView play];
//   // self.bgImage.image = nil;
//}
//
//- (void)pause {
//    [_playerView pause];
//}
////重新播放
//-(void)replay {
//    [_playerView replay];
//}
////播放速度
//-(CGFloat)rate {
//    return [_playerView rate];
//}
////取消播放
//-(void)cancelLoading {
//    [_playerView cancelPlayer];
//}

#pragma mark -- 创建自动轮播
-(SDCycleScrollView *)sdCycleView {
    if (!_sdCycleView) {
        _sdCycleView = [[SDCycleScrollView alloc]init];
        _sdCycleView.showPageControl = YES;
        _sdCycleView.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        _sdCycleView.frame = self.view.bounds;
        _sdCycleView.bannerImageViewContentMode = UIViewContentModeScaleAspectFit;
        _sdCycleView.backgroundColor = [UIColor blackColor];
        [self.view insertSubview:_sdCycleView atIndex:0];
    }
    return _sdCycleView;
}

#pragma mark -- 创建播放器
-(void)setPlayerWithUrl:(NSString *)url {
//    _playerView = [[HJPlayerView alloc]initWithVideoUrl:url];
//    _playerView.frame = self.view.bounds;
//    _playerView.delegate = self;
//    _playerView.videoContent = AVLayerVideoGravityResizeAspect;
//    [self.bgImage addSubview:_playerView];
//    [self.view insertSubview:_playerView atIndex:0];
}


//-(void)onProgressUpdate:(CGFloat)current total:(CGFloat)total {
//    LKLog(@"current=%lf,total=%lf",current,total);
//    if ([self rate] == total && self.isPlayerReady) {
//        [self performSelector:@selector(replay) withObject:nil];
//    }
//}
//-(void)onPlayItemStatusUpdate:(AVPlayerItemStatus)status {
//    switch (status) {
//        case AVPlayerItemStatusFailed:
//            LKLog(@"item 有误");
//            break;
//        case AVPlayerItemStatusReadyToPlay:
//            LKLog(@"准好播放了");
//            [self hideTextHud];
//            self.isPlayerReady = YES;
//            [self performSelector:@selector(play) withObject:nil];
//            break;
//        case AVPlayerItemStatusUnknown:
//            LKLog(@"视频资源出现未知错误");
//            [self hideTextHud];
//            [self showErrorHUDWithError:@"视频资源出现未知错误"];
//            break;
//        default:
//            break;
//    }
//}


- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self resume];
}



- (void)dealloc {
    [self destoryPlayer];
}
- (void)pause {
    [self.player pausePlay];
}

- (void)resume {
    [self.player resumePlay];
}

- (void)destoryPlayer {
    [self.player removeVideo];
}
-(HJVideoPlayer *)player {
    if (!_player) {
        _player = [HJVideoPlayer new];
        _player.delegate = self;
    }
    return _player;
}
#pragma mark--HJVideoPlayerDelegate 播放代理
- (void)player:(HJVideoPlayer *)player statusChanged:(HJVideoPlayerStatus)status {
    switch (status) {
        case HJVideoPlayerStatusUnload:   // 未加载
            break;
        case HJVideoPlayerStatusPrepared:   // 准备播放
            break;
        case HJVideoPlayerStatusLoading: // 加载中
            break;
        case HJVideoPlayerStatusPlaying:// 播放中
            break;
        case HJVideoPlayerStatusPaused: // 暂停
            break;
        case HJVideoPlayerStatusEnded:// 播放结束
        {
            // 重新开始播放
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.player resetPlay];
            });
        }
            break;
        case HJVideoPlayerStatusError: // 错误
            break;
        default:
            break;
    }
}

-(void)player:(HJVideoPlayer *)player currentTime:(float)currentTime totalTime:(float)totalTime progress:(float)progress {
    
}


@end
